/* eslint-env node */

import fs from 'node:fs';
import path from 'node:path';
import { spawn } from 'node:child_process';

const aliasToFile = {
  dev: 'features.dev.json',
  lite: 'features.lite.json',
  prod: 'features.prod.json',
  test: 'features.test.json',
};

function pickFeaturesArg(argv) {
  for (const raw of argv) {
    if (!raw) continue;
    const arg = String(raw).trim();
    // 这里忽略到处理--开头的参数 例如--parallel, --any, or -p
    if (arg.startsWith('-')) continue;
    const normalized = arg.startsWith('@') ? arg.slice(1) : arg;
    if (aliasToFile[normalized]) return aliasToFile[normalized];
    if (normalized.endsWith('.json')) return normalized;
    const abs = path.isAbsolute(normalized) ?
      normalized :
      path.resolve(process.cwd(), normalized);
    if (fs.existsSync(abs) && fs.statSync(abs).isFile()) return normalized;
  }
  return null;
}

function ensureFileExists(relativeOrAbsolutePath) {
  const absolutePath = path.isAbsolute(relativeOrAbsolutePath) ?
    relativeOrAbsolutePath :
    path.resolve(process.cwd(), relativeOrAbsolutePath);
  if (!fs.existsSync(absolutePath)) {
    throw new Error(`Features file not found: ${absolutePath}`);
  }
  return absolutePath;
}

function run(command, args, options = {}) {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, {
      stdio: 'inherit',
      shell: true,
      ...options,
    });
    child.on('exit', (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(new Error(`${command} ${args.join(' ')} exited with code ${code}`));
      }
    });
    child.on('error', reject);
  });
}

async function main() {
  const args = process.argv.slice(2);
  const selectedFileName = pickFeaturesArg(args) || aliasToFile.dev;
  const featuresFileAbsPath = ensureFileExists(selectedFileName);

  await run('node', ['scripts/dev/pack-svg-icons.js']);

  const env = { ...process.env, BUILD_PATH: 'dist' };
  await run('craco', ['build'], { env });

  const distDir = path.resolve(process.cwd(), 'dist');
  if (!fs.existsSync(distDir)) {
    throw new Error(`Build output folder not found: ${distDir}`);
  }

  const jsonText = fs.readFileSync(featuresFileAbsPath, 'utf8');
  JSON.parse(jsonText);

  const outPath = path.join(distDir, 'features.json');
  fs.writeFileSync(outPath, jsonText, 'utf8');

  process.stdout.write(
    `features.json generated from ${path.basename(featuresFileAbsPath)} at ${outPath}\n`,
  );
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});